// pages/i/order-boot.js
const auth = require('../../utils/auth.js')
const bizPayService = require('../../services/bizPay.js')
const bizGoodsService = require('../../services/bizGoods.js')
const bizOrderService = require('../../services/bizOrder.js')
const orderService = require('../../services/order.js')

import Dialog from '@vant/weapp/dialog/dialog';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeIndex: 0,
        isLoggedIn: false,
        userInfo: null,
        hadBindPhone: false,
        loginReady: false,

        // 支付记录相关
        payRecordTab:'all',
        payRecords: [],
        loading: false,
        hasMore: true,
        currentPage: 1,
        pageSize: 10,
        payRecordVisible: false,

        // 支付记录详情相关
        payRecordDetail: null,
        detailLoading: false,
        detailError: null,
        currentRecordId: null,

        // 消费订单相关
        consumptionTab:'all',
        consumptionOrders: [],
        consumptionLoading: false,
        consumptionHasMore: true,
        consumptionCurrentPage: 1,
        consumptionPageSize: 10,

        // 严选订单
        orderTab:'all',
        orders: [],
        ordersLoading: false,
        ordersHasMore: true,
        ordersCurrentPage: 1,
        ordersPageSize: 10,

        showComplaintDialog: false,
        complaintContent: '',
        submittingComplaint: false,

        // 搜索
        searchVisible:false,
        keyword:'',
        searchTip:'按照商家名称搜索'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.checkLoginStatus()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (this.data.loginReady == false) {
            this.checkLoginStatus()

            const app = getApp();
            const tabParam = app.globalData.tabParam;
            if (tabParam) {
                app.globalData.tabParam = null;
                if(tabParam.type == 'biz-order'){
                    this.setData({
                        activeIndex: 1,
                        consumptionTab: tabParam.status,
                    },function(){
                        this.loadConsumptionOrders();
                    })
                }else if(tabParam.type == 'store-order'){
                    this.setData({
                        activeIndex: 2,
                        orderTab: tabParam.status,
                    },function(){
                        this.loadOrders();
                    })
                }
            }else{
                if (this.data.activeIndex == 1) {
                    this.loadConsumptionOrders()
                } else if (this.data.activeIndex == 0) {
                    this.loadPayRecords()
                } else if (this.data.activeIndex == 2) {
                    this.loadOrders()
                }
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        if (this.data.activeIndex == 1) {
            this.refreshConsumptionOrders().finally(() => {
                wx.stopPullDownRefresh()
            })
        } else if (this.data.activeIndex == 0) {
            this.refreshPayRecords().finally(() => {
                wx.stopPullDownRefresh()
            })
        } else if (this.data.activeIndex == 2) {
            this.refreshOrders().finally(() => {
                wx.stopPullDownRefresh()
            })
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.activeIndex == 1 && this.data.consumptionHasMore && !this.data.consumptionLoading) {
            this.loadMoreConsumptionOrders()
        } else if (this.data.activeIndex == 0 && this.data.hasMore && !this.data.loading) {
            this.loadMorePayRecords()
        } else if (this.data.activeIndex == 2 && this.data.ordersHasMore && !this.data.ordersLoading) {
            this.loadMoreOrders()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        let type = e.target.dataset.type
        let title = e.target.dataset.title
        let url = e.target.dataset.url
        let id = e.target.dataset.id

        let path = ''
        if (type == 'bizorder') {
            path = `/pages/biz/goods?id=${id}`
        } else if (type == 'pay') {
            path = `/pages/biz/detail?id=${id}`
        }

        return {
            title: title,
            path: path,
            imageUrl: url
        }
    },

    /**
     * 菜单点击事件
     */
    handleMenuClick(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            activeIndex: index
        },function(){

            // 如果切换到消费订单菜单，加载消费订单
            if (index == 1 && this.data.loginReady) {
                this.setData({
                    searchTip:'按照商品名称搜索',
                    keyword:''
                })
                this.loadConsumptionOrders()
            }
            // 如果切换到支付记录菜单，加载支付记录
            else if (index == 0 && this.data.loginReady) {
                this.setData({
                    searchTip:'按照商家名称搜索',
                    keyword:''
                })
                this.loadPayRecords()
            }
            // 如果切换到严选订单菜单，加载严选订单
            else if (index == 2 && this.data.loginReady) {
                this.setData({
                    searchTip:'按照商品名称搜索',
                    keyword:''
                })
                this.loadOrders()
            }
        });
    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus()
            const hadBindPhone = loginStatus.isLoggedIn && auth.isValidUserInfo(loginStatus.userInfo);
            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true,
                hadBindPhone: hadBindPhone
            })

            if (hadBindPhone) {
                this.loadPayRecords()
            }

        } catch (error) {
            console.error('检查登录状态失败:', error)
            // 检查失败时也跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
        }
    },

    /**
     * 加载支付记录列表
     */
    async loadPayRecords() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            const result = await bizPayService.getPayRecords({
                page: 1,
                limit: this.data.pageSize,
                range:this.data.payRecordTab,
                keyword:this.data.keyword
            })

            if (result.success) {
                const { list, total, has_more } = result.data

                this.setData({
                    payRecords: list || [],
                    hasMore: has_more,
                    currentPage: 1
                })

                console.log('支付记录列表:', list)
            } else {
                wx.showToast({
                    title: result.message || '获取支付记录失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载支付记录失败:', error)
            wx.showToast({
                title: '获取支付记录失败',
                icon: 'none'
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    /**
     * 加载更多支付记录
     */
    async loadMorePayRecords() {
        if (this.data.loading || !this.data.hasMore) return

        this.setData({ loading: true })

        try {
            const nextPage = this.data.currentPage + 1
            const result = await bizPayService.getPayRecords({
                page: nextPage,
                limit: this.data.pageSize,
                range:this.data.payRecordTab,
                keyword:this.data.keyword
            })

            if (result.success) {
                const { list, has_more } = result.data

                if (list && list.length > 0) {
                    this.setData({
                        payRecords: [...this.data.payRecords, ...list],
                        hasMore: has_more,
                        currentPage: nextPage
                    })
                } else {
                    this.setData({
                        hasMore: false
                    })
                }
            } else {
                wx.showToast({
                    title: result.message || '加载更多失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载更多支付记录失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    /**
     * 刷新支付记录
     */
    async refreshPayRecords() {
        this.setData({
            payRecords: [],
            hasMore: true,
            currentPage: 1
        })

        await this.loadPayRecords()
    },

    /**
     * 加载消费订单列表
     */
    async loadConsumptionOrders() {
        if (this.data.consumptionLoading) return

        this.setData({ consumptionLoading: true })

        try {
            const result = await bizGoodsService.getOrderList(1, this.data.consumptionPageSize,this.data.consumptionTab,this.data.keyword)

            if (result.success) {
                const { list, total, has_more } = result.data

                this.setData({
                    consumptionOrders: list || [],
                    consumptionHasMore: has_more,
                    consumptionCurrentPage: 1
                })

                console.log('消费订单列表:', list)
            } else {
                wx.showToast({
                    title: result.message || '获取消费订单失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载消费订单失败:', error)
            wx.showToast({
                title: '获取消费订单失败',
                icon: 'none'
            })
        } finally {
            this.setData({ consumptionLoading: false })
        }
    },

    /**
     * 加载更多消费订单
     */
    async loadMoreConsumptionOrders() {
        if (this.data.consumptionLoading || !this.data.consumptionHasMore) return

        this.setData({ consumptionLoading: true })

        try {
            const nextPage = this.data.consumptionCurrentPage + 1
            const result = await bizGoodsService.getOrderList(nextPage, this.data.consumptionPageSize,this.data.consumptionTab,this.data.keyword)

            if (result.success) {
                const { list, has_more } = result.data

                if (list && list.length > 0) {
                    this.setData({
                        consumptionOrders: [...this.data.consumptionOrders, ...list],
                        consumptionHasMore: has_more,
                        consumptionCurrentPage: nextPage
                    })
                } else {
                    this.setData({
                        consumptionHasMore: false
                    })
                }
            } else {
                wx.showToast({
                    title: result.message || '加载更多失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载更多消费订单失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ consumptionLoading: false })
        }
    },

    /**
     * 刷新消费订单
     */
    async refreshConsumptionOrders() {
        this.setData({
            consumptionOrders: [],
            consumptionHasMore: true,
            consumptionCurrentPage: 1
        })

        await this.loadConsumptionOrders()
    },

    /**
     * 处理订单操作
     */
    handleOrderAction(e) {
        const { orderId, action } = e.currentTarget.dataset

        if (action === 'comment') {
            // 跳转到评价页面
            wx.navigateTo({
                url: `/pages/i/comment?order_id=${orderId}&type=biz-order`
            })
        } else if (action === 'detail') {
            // 跳转到订单详情页面
            wx.navigateTo({
                url: `/pages/i/order-detail?order_id=${orderId}`
            })
        } else if (action === 'refund') {
            // 跳转到订单退款页面
            wx.navigateTo({
                url: `/pages/i/order-refund?order_id=${orderId}`
            })
        }
    },

    toBizDetail(e) {
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/biz/detail?id=${id}`
        })
    },

    /**
     * 随心付订单补差价
     */
    async doBuPay(e) {
        const record_id = e.currentTarget.dataset.id

        try {
            wx.showLoading({ title: '正在发起支付...' })

            const result = await bizPayService.payRemainMoney(record_id)

            if (result.success) {
                const { wx_pay_config, pay_record_id, remain_money } = result.data

                // 调起微信支付
                wx.requestPayment({
                    ...wx_pay_config,
                    success: (res) => {
                        console.log('补差价支付成功:', res)
                        wx.showToast({
                            title: '补差价支付成功',
                            icon: 'success'
                        })

                        // 刷新支付记录列表
                        this.refreshPayRecords()
                    },
                    fail: (err) => {
                        console.error('补差价支付失败:', err)
                        if (err.errMsg.includes('cancel')) {
                            wx.showToast({
                                title: '支付已取消',
                                icon: 'none'
                            })
                        } else {
                            wx.showToast({
                                title: '支付失败，请重试',
                                icon: 'none'
                            })
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: result.message || '发起支付失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('补差价支付异常:', error)
            wx.showToast({
                title: '支付异常，请重试',
                icon: 'none'
            })
        } finally {
            wx.hideLoading()
        }
    },

    handlePayRecordComment(e) {
        const record_id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/i/comment?order_id=${record_id}&type=pay`
        })
    },

    /**
     * 查看支付记录详情
     */
    handlePayRecordDetail(e) {
        const record_id = e.currentTarget.dataset.id
        this.setData({
            currentRecordId: record_id,
            payRecordVisible: true,
            payRecordDetail: null,
            detailError: null
        })
        this.loadPayRecordDetail()
    },

    /**
     * 关闭支付记录详情弹窗
     */
    closePayRecordDetail() {
        this.setData({
            payRecordVisible: false,
            payRecordDetail: null,
            detailError: null
        })
    },

    /**
     * 加载支付记录详情
     */
    async loadPayRecordDetail() {
        if (!this.data.currentRecordId) {
            return
        }

        this.setData({
            detailLoading: true,
            detailError: null
        })

        try {
            const result = await bizPayService.getPayRecordDetail(this.data.currentRecordId)

            if (result.success) {
                this.setData({
                    detailLoading: false,
                    payRecordDetail: result.data
                })
            } else {
                this.setData({
                    detailLoading: false,
                    detailError: result.message
                })
            }
        } catch (error) {
            console.error('加载支付记录详情失败:', error)
            this.setData({
                detailLoading: false,
                detailError: error.message || '加载失败'
            })
        }
    },

    /**
     * 格式化时间
     */
    formatTime(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp * 1000);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    /**
     * 格式化金额
     */
    formatMoney(amount) {
        if (amount === null || amount === undefined) return '0.00';
        return parseFloat(amount).toFixed(2);
    },

    /**
     * 获取支付状态文本
     */
    getPayStatusText(status) {
        const statusMap = {
            0: '未支付',
            1: '已支付'
        };
        return statusMap[status] || '未知状态';
    },

    /**
     * 拨打电话
     */
    callPhone(e) {
        const phone = e.currentTarget.dataset.phone;
        if (phone) {
            wx.makePhoneCall({
                phoneNumber: phone,
                fail: (err) => {
                    console.error('拨打电话失败:', err);
                    wx.showToast({
                        title: '拨打电话失败',
                        icon: 'none'
                    });
                }
            });
        }
    },

    /**
     * 跳转到商家详情
     */
    goToBizDetail() {
        if (this.data.payRecordDetail && this.data.payRecordDetail.biz && this.data.payRecordDetail.biz.id) {
            wx.navigateTo({
                url: `/pages/biz/detail?id=${this.data.payRecordDetail.biz.id}`
            });
        }
    },

    goToLogin() {
        wx.navigateTo({
            url: '/pages/index/login'
        })
    },

    // 严选订单
    toGoodsDetail(e) {
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/store/pages/goods/detail?id=${id}`
        })
    },

    async handleStoreOrderAction(e) {
        const { orderId, action } = e.currentTarget.dataset

        if (action === 'pay') {
            /**
             * 1、检查当前用户信息是否可以支付
             * 2、进行支付
             */
            const canPayResult = await orderService.checkCanPay(orderId);
            if (canPayResult.success) {
                wx.showLoading({
                    title: '去支付...',
                    mask: true,
                    complete: () => {
                        setTimeout(() => {
                            wx.hideLoading();
                            wx.navigateTo({
                                url: `/store/pages/goods/pay?order_id=${orderId}`
                            })
                        }, 1000);
                    }
                })
            } else {
                wx.showToast({
                    title: canPayResult.message,
                    icon: 'none'
                })
            }
        } else if (action === 'detail') {
            wx.navigateTo({
                url: `/pages/i/order?order_id=${orderId}`
            })
        } else if (action === 'refund') {
            wx.navigateTo({
                url: `/pages/i/store-order-refund?order_id=${orderId}`
            })
        } else if (action === 'comment') {
            wx.navigateTo({
                url: `/pages/i/comment?order_id=${orderId}&type=store-order`
            })
        }
    },

    async loadOrders() {
        if (this.data.ordersLoading) return

        this.setData({ ordersLoading: true })

        try {
            const result = await orderService.getOrderList(1, this.data.ordersPageSize,this.data.orderTab,this.data.keyword)

            if (result.success) {
                const { list, total, has_more } = result.data

                this.setData({
                    orders: list || [],
                    ordersHasMore: has_more,
                    ordersCurrentPage: 1
                })

                console.log('消费订单列表:', list)
            } else {
                wx.showToast({
                    title: result.message || '获取消费订单失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载消费订单失败:', error)
            wx.showToast({
                title: '获取消费订单失败',
                icon: 'none'
            })
        } finally {
            this.setData({ ordersLoading: false })
        }
    },

    /**
     * 加载更多消费订单
     */
    async loadMoreOrders() {
        if (this.data.ordersLoading || !this.data.ordersHasMore) return

        this.setData({ ordersLoading: true })

        try {
            const nextPage = this.data.ordersCurrentPage + 1
            const result = await orderService.getOrderList(nextPage, this.data.ordersPageSize,this.data.orderTab,this.data.keyword)

            if (result.success) {
                const { list, has_more } = result.data

                if (list && list.length > 0) {
                    this.setData({
                        orders: [...this.data.orders, ...list],
                        ordersHasMore: has_more,
                        ordersCurrentPage: nextPage
                    })
                } else {
                    this.setData({
                        ordersHasMore: false
                    })
                }
            } else {
                wx.showToast({
                    title: result.message || '加载更多失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载更多严选订单失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ ordersLoading: false })
        }
    },

    /**
     * 刷新消费订单
     */
    async refreshOrders() {
        this.setData({
            orders: [],
            ordersHasMore: true,
            ordersCurrentPage: 1
        })

        await this.loadOrders()
    },

    onRightOpen(e) {
        console.log('onRightOpen', e)
    },

    onRightClose(e) {
        console.log('onRightClose', e)
    },

    // 删除一条记录
    async deletePayRecord(e) {
        const id = e.currentTarget.dataset.id;
        Dialog.confirm({
            title: '温馨提醒',
            message: '确定要删除该支付记录吗？',
        })
            .then(async () => {
                // on confirm
                const result = await bizPayService.doHide(id)
                if (result.success) {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    this.refreshPayRecords();
                } else {
                    wx.showToast({
                        title: result.message,
                        icon: 'none'
                    })
                }
            })
            .catch(() => {
                // on cancel
            });
    },

    async deleteBizGoodsOrder(e) {
        const id = e.currentTarget.dataset.id;
        Dialog.confirm({
            title: '温馨提醒',
            message: '确定要删除该订单吗？',
        })
            .then(async () => {
                const result = await bizOrderService.doHide(id)
                if (result.success) {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    this.refreshConsumptionOrders()
                }
                else {
                    wx.showToast({
                        title: result.message,
                        icon: 'none'
                    })
                }
            })
            .catch(() => {
                // on cancel
            });
    },

    async deleteOrder(e) {
        const id = e.currentTarget.dataset.id;
        Dialog.confirm({
            title: '温馨提醒',
            message: '确定要删除该订单吗？',
        })
            .then(async () => {
                const result = await orderService.doHide(id)
                if (result.success) {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    this.refreshOrders()
                }
                else {
                    wx.showToast({
                        title: result.message,
                        icon: 'none'
                    })
                }
            })
            .catch(() => {
                // on cancel
            });
    },

    showComplaintDialog(e) {
        this.setData({
            showComplaintDialog: true,
            complaintContent: '',
        })
    },

    async submitComplaint() {
        if (!this.data.complaintContent.trim()) {
            wx.showToast({ title: '请输入投诉内容', icon: 'none' });
            return;
        }
        this.setData({ submittingComplaint: true });
        const res = await bizPayService.complaint(this.data.payRecordDetail.record.id, this.data.complaintContent);
        this.setData({ submittingComplaint: false });
        if (res.success) {
            wx.showToast({ title: '投诉提交成功', icon: 'success' });
            this.setData({ showComplaintDialog: false });
        } else {
            wx.showToast({ title: res.message, icon: 'none' });
        }
    },

    onComplaintDialogClose() {
        this.setData({ showComplaintDialog: false });
    },

    handlePayRecordsTabsChange(e){
        let v = e.detail.name;
        this.setData({
            payRecordTab:v
        },function(){
            this.refreshPayRecords();
        })
    },

    handleBizOrderTabsChange(e){
        let v = e.detail.name;
        this.setData({
            consumptionTab:v
        },function(){
            this.refreshConsumptionOrders();
        })
    },

    handleStoreOrderTabsChange(e){
        let v = e.detail.name;
        this.setData({
            orderTab:v
        },function(){
            this.refreshOrders();
        })
    },

    showSearch(){
        this.setData({
            searchVisible:!this.data.searchVisible
        })
    },

    onSearch(e){
        this.setData({
            keyword:e.detail
        },function(){
            if(this.data.activeIndex == 0){
                this.refreshPayRecords();
            }else if(this.data.activeIndex == 1){
                this.refreshConsumptionOrders();
            }else if(this.data.activeIndex == 2){
                this.refreshOrders();
            }
        })
    }
})